package com.mvvm.start.common.network

/**
 * @功能:
 * @User Lmy
 * @Creat 2021/9/17 10:26 上午
 * @Compony 永远相信美好的事情即将发生
 */
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import androidx.annotation.RequiresPermission
import com.mvvm.start.base.BaseApplication
import com.mvvm.start.base.utils.NetworkCallbackImpl

/**
  * @功能: 新的网络状态监听
  * @User Lmy
  * @Creat 2021/9/17 10:52 上午
  * @Compony 永远相信美好的事情即将发生
  */
object NetworkStateClient {

    private val mNetworkCallback = NetworkCallbackImpl()

    /**
     * 注册网络监听客户端
     * @return Unit
     */
    @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
    fun register() {
        val build = NetworkRequest.Builder().build()
        val cm = BaseApplication.application.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        cm.registerNetworkCallback(build, mNetworkCallback)
    }

    /**
     * 获取网络类型 其他类型的网络归为了WIFI，如果需要细分，可以对[NetworkCallbackImpl]进行追加分类
     * @return Int WIFI:[NetworkCapabilities.TRANSPORT_WIFI]、移动网络:[NetworkCapabilities.TRANSPORT_CELLULAR]
     */
    fun getNetworkType(): Int = mNetworkCallback.currentNetworkType

    /**
     * 网络是否连接
     * @return Boolean
     */
    fun isConnected(): Boolean = mNetworkCallback.isConnected
}
